package com.changgou.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.pay.service.WeixinPayService;
import com.changgou.util.HttpClient;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author tang.qingbo
 * @Date 2020/9/6 21:39
 * @Version 1.0
 */
@Service
public class WeixinPayServiceImpl implements WeixinPayService {

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.partner}")
    private String partner;

    @Value("${weixin.partnerkey}")
    private String partnerKey;

    @Value("${weixin.notifyurl}")
    private String notifyurl;

    /**
     * 生成二维码
     * @return 返回页面需要的参数信息
     */
    @Override
    public Map createNative(Map<String,String> dataMap) {
        try {
            //封装请求参数信息
            Map param = new HashMap();
            //公众账号id
            param.put("appid", appid);
            //商户号
            param.put("mch_id", partner);
            //随机字符串
            param.put("nonce_str", WXPayUtil.generateNonceStr());
            //商品描述
            param.put("body", "畅购商品支付测试");
            //商户订单号
            param.put("out_trade_no", dataMap.get("outtradeno"));
            //标价金额
            param.put("total_fee", dataMap.get("totalfee"));
            //终端ip
            param.put("spbill_create_ip", "127.0.0.1");
            //通知地址
            param.put("notify_url", notifyurl);
            //交易类型
            param.put("trade_type", "NATIVE");

            //队列参数信息
            Map<String, String> attachMap = new HashMap<>();
            attachMap.put("queue", dataMap.get("queue"));
            attachMap.put("exchange", dataMap.get("exchange"));
            //用户名
            String username = dataMap.get("username");
            if (!StringUtils.isEmpty(username)) {
                attachMap.put("username", username);
            }
            //将参数转换为json格式
            String jsonAttach = JSON.toJSONString(attachMap);

            param.put("attach", jsonAttach);

            //将map类型的参数转为xml,并携带签名
            String paramXml = WXPayUtil.generateSignedXml(param, partnerKey);

            //执行http请求
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            httpClient.setHttps(true);
            httpClient.setXmlParam(paramXml);
            httpClient.post();

            //获取参数
            String content = httpClient.getContent();
            //将xml数据转为map
            Map<String, String> stringMap = WXPayUtil.xmlToMap(content);
            System.out.println("返回的结果数据: " + stringMap);

            //返回结果数据
            return stringMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询订单状态
     *
     * @param outTradeNo 商户订单号
     * @return 返回状态信息
     */
    @Override
    public Map queryPayStatus(String outTradeNo) {
        try {
            //封装请求参数信息
            Map param = new HashMap();
            //公众账号ID
            param.put("appid", appid);
            //商户号
            param.put("mch_id", partner);
            //商户订单号
            param.put("out_trade_no", outTradeNo);
            //随机字符串
            param.put("nonce_str", WXPayUtil.generateNonceStr());

            //将map参数信息转换为xml,并带上签名
            String paramXml = WXPayUtil.generateSignedXml(param, partnerKey);

            //发送请求
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setHttps(true);
            httpClient.setXmlParam(paramXml);
            httpClient.post();

            //获取返回结果
            String content = httpClient.getContent();
            //转换结果并返回
            return WXPayUtil.xmlToMap(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭支付
     *
     * @param orderId 需要关闭的订单号
     * @return
     */
    @Override
    public Map closePay(String orderId) {
        try {
            //封装请求数据
            Map<String, String> dataMap = new HashMap<>();
            dataMap.put("appid", appid);
            dataMap.put("mch_id", partner);
            dataMap.put("out_trade_no", orderId);
            dataMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //转换成xml格式并生成签名
            String reqParam = WXPayUtil.generateSignedXml(dataMap, partnerKey);

            //发送请求
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/closeorder");
            httpClient.setHttps(true);
            httpClient.setXmlParam(reqParam);
            httpClient.post();

            //获取响应内容
            String content = httpClient.getContent();
            //将响应内容转为map
            return WXPayUtil.xmlToMap(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
